package dockerfile

import (
	"context"
	"docker/internal/svc"
	"docker/internal/types"
	model "docker/model/mongo"
	"docker/utils"
	"fmt"
	"github.com/jinzhu/copier"
	"go.mongodb.org/mongo-driver/bson/primitive"

	"github.com/zeromicro/go-zero/core/logx"
)

type GenerateDockerfileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGenerateDockerfileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GenerateDockerfileLogic {
	return &GenerateDockerfileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GenerateDockerfileLogic) GenerateDockerfile(req *types.DockerfileStageReq) (resp *types.StringResp, err error) {
	// todo: add your logic here and delete this line
	stages := req.DockerfileStages
	var dss []utils.DockerfileStage
	for _, stage := range stages {
		var ds utils.DockerfileStage
		copier.Copy(&ds, &stage)
		cmds := stage.DockerfileCmds
		var dcs []utils.DockerfileCmdLine
		for _, cmd := range cmds {
			var dc utils.DockerfileCmdLine
			copier.Copy(&dc, &cmd)
			dockerfileCmd := utils.GetDockerfileCmd(cmd.DockerfileCmd)
			dc.DockerfileCmd = dockerfileCmd
			dcs = append(dcs, dc)
		}
		ds.DockerfileCmdLines = dcs
		dss = append(dss, ds)
	}

	dockerfile, err := utils.GenerateDockerfile(dss...)
	fmt.Println(dockerfile)

	var dfs []model.DockerfileStage
	for _, stage := range stages {
		var ds model.DockerfileStage
		copier.Copy(&ds, &stage)
		cmds := stage.DockerfileCmds
		var dcs []model.DockerfileCmd
		for _, cmd := range cmds {
			var dc model.DockerfileCmd
			copier.Copy(&dc, &cmd)
			dcs = append(dcs, dc)
		}
		ds.DockerfileCmds = dcs
		dfs = append(dfs, ds)
	}

	var df model.Dockerfile
	df.Name = req.Name
	df.Content = dockerfile
	df.DockerfileStages = dfs

	if len(req.Id) != 0 {
		objectID, _ := primitive.ObjectIDFromHex(req.Id)
		df.ID = objectID
		l.svcCtx.DockerfileModel.Update(l.ctx, &df)
	} else {
		l.svcCtx.DockerfileModel.Insert(l.ctx, &df)
	}

	return &types.StringResp{
		Result: types.Result{
			Code:      200,
			Message:   "",
			ExtInfo:   "",
			Timestamp: 0,
		},
		Data: dockerfile,
	}, err
}
